package com.datastructures2.背包队列栈;

import java.util.Iterator;
import java.util.Objects;

/**
 * 可动态调整数组大小的栈
 * @author MaoLin Wang
 * @date 2020/2/2910:07
 */
public class ResizeArrayStack<Item> implements  Iterable<Item> {
    private int size;
    private Item[] stack= (Item[]) new Object[1];

    public void push(Item item){
        if (this.size==this.stack.length){
            resize(2*this.stack.length);
        }
        this.stack[this.size++]=item;
    }
    public Item pop(){
        if (isEmpty()){
            return null;
        }
        return this.stack[this.size--];
    }
    public int size(){
        return this.size;
    }
    public void  resize(int length){
        Item[]items= (Item[]) new Object[length];
        for (int i = 0; i < this.stack.length; i++) {
            items[i]=this.stack[i];
        }
        this.stack =items;
    }
    public boolean isEmpty(){
        return size==0;
    }
    @Override
    public Iterator<Item> iterator() {
        return new ListIterator<>();
    }

    private class ListIterator<Item>  implements Iterator<Item>{

        private int N=size;


        @Override
        public boolean hasNext() {

            return N>0;
        }

        @Override
        public Item next() {
            return (Item) stack[--N];
        }
    }

    public static void main(String[] args) {
        ResizeArrayStack<Object> stack = new ResizeArrayStack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        System.out.println("size"+stack.size());
        Iterator<Object> iterator = stack.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        System.out.println("size"+stack.size());

    }
}
